<?php
namespace Home\Controller;

use Think\Controller;

class Test
{
	public $code;
	public $msg;
	public $count;
	public $data;
}

class UserController extends Controller
{
    public function showLogin()//显示登陆界面
    {
        $this->display('login');
    }

    public function login()//登陆
    {
        if(!empty($_POST)) 
        {
            $user = D("User");//实例化User对象
            $verify = new \Think\Verify();
            $flag = $verify->check($_POST['checkcode']);//检测验证码是否输入正确
            if ($flag == false) //验证码错误
            {
                $return['status']=0;
                $return['info']='验证码错误';
                $this->ajaxReturn($return);
            } 
            else  //验证码输入正确
            {
                $where['num'] = I('post.num');
                $where['password'] = md5(I('post.password'));
                $result = $user->field('status,id')->where($where)->find();//查找登陆用户是否存在 
                if ($result['status'] > 0) { //该用户存在 且权限足够
                    session('status', $result['status']);
                    session('id', $result['id']);
                    $return['status']=1;
                    $this->ajaxReturn($return);
                } 
                else 
                {//该用户不存在 或已被注销
                    $return['status']=0;
                    $return['info']='用户名或密码错误';
                    $this->ajaxReturn($return);
                }
            }
        }
    }
    
    public function verifyImg()//显示验证码
    {
        //设置验证码的宽高字体大小以及验证码的个数
        $config = array(
            'imageW' => 150,
            'imageH' => 40,
            'bg'        =>  array(243, 251, 254),
            'useCurve'  =>  false, 
            'useNoise'  =>  false,
            'fontSize' => 20,
            'length' => 4
        );
        $obj = new \Think\Verify($config);
        $obj->entry();//显示验证码
    }

    public function showSelf()//显示个人信息
    {
        if(session('status')>0)
        {
            $this->display('User_inf');
        }  
    }

    public function getSelf()//获取个人信息
    {
        $user=M('User');
        $where['id']=session('id');
        $result=$user->field('id,num,name,sex,class,school,group,status,password')->where($where)->find();
        $this->ajaxReturn($result);
    }
    public function getname()
    {
        $user=M('User');
        $where['id']=session('id');
        $result=$user->field('name')->where($where)->find();
        $this->ajaxReturn($result);
    }
    public function showAlterSelf()//显示修改个人信息页面
    {
        if(session('status')>0)
        {
            $this->display('Alter_Personal');
        }
    }

    public function alterSelf()//修改个人信息
    {
        if(!empty($_POST))
        {
            if(I('post.pass_status')==1)//修改密码
            {
                $user = D('User');
                $where['id'] = session('id');//传回修改用户的id
                $date['name'] = I('post.name');//更新的数据
                $date['password']=md5(I('post.repassword'));//修改后的密码
                $date['sex'] = I('post.sex');//更新的数据
                $date['class'] = I('post.class');///更新的数据
                $date['school'] = I('post.school');//更新的数据
                $date['status'] = I('post.status');//更新的数据
                $date['group']=I('post.group');//更新的数据
            }
            else//不修改密码
            {
                $user = D('User');
                $where['id'] = session('id');//传回修改用户的id
                $date['name'] = I('post.name');//更新的数据
                $date['sex'] = I('post.sex');//更新的数据
                $date['class'] = I('post.class');///更新的数据
                $date['school'] = I('post.school');//更新的数据
                $date['status'] = I('post.status');//更新的数据
                $date['group']=I('post.group');//更新的数据
            }
            if (!$user->create($date))//修改失败
            {
                $return['status']=0;
                $return['info']=$user->getError();//返回错误信息
                $this->ajaxReturn($return);
            }
            else
            {
                $result = $user->where($where)->save($date);//更新数据
                if ($result)//修改成功
                {
                    $return['status']=1;
                    $this->ajaxReturn($return);
                } 
                else//修改失败
                {
                    $return['status']=0;
                    $return['info']='修改失败';
                    $this->ajaxReturn($return);//返回错误信息
                }
            } 
        }
    }

    public function showUser()//显示所有的学生信息
    {
        if(session('status')>1)//权限验证
        {
            $user=D('User');
            $result=$user->where('status>0')->field('id,num,name,sex,class,school,group,status')->order('status desc,num')->select();//显示user表中有效的用户信息
            $this->assign('result',$result);//渲染模板
            $this->display("All_User");
        }
        else//权限不足
        {
            $this->error('权限不足');
        }
    }

    public function getmsg($page,$limit)//返回所有用户信息
    {
        $test=new Test();//分页类
		$user=M('User');
		$start=($page-1)*$limit;
        $info = $user
            ->field('id,num,name,sex,class,school,group,status')
            ->order('id desc')
            ->where('status>0')
            ->limit($start,$limit)
            ->select();//遍历note
        $count = $user->count();
        $test->code = 0;
        $test->msg = "";
        $test->count = $count;
        $test->data = $info;
        $this->ajaxReturn($test);//返回数据对象
    }

    public function showAddUser()//显示添加用户页面
    {
        if(session('status')>1)
        {
            $this->display('addUser');
        }
        else//权限不足
        {
            $this->error('权限不足');
        }
    }

    public function addUser()//添加用户
    {
        $user = M('User');
        if ($user->create())//创建user对象 获取表单中的值
        {
            $user->password=md5(I('post.password'));
            $where['num']=I('post.num');
            $result=$user->where($where)->find();//查找是否存在重复的用户
            if(empty($result))//不存在重复的用户
            {
                $user->add();//将数据插入数据库
                $return['status']=1;
                $return['info']='添加成功';
                $this->ajaxReturn($return);
            }
            else//存在重复的用户
            {
                $return['status']=0;
                $return['info']='用户名已存在';
                $this->ajaxReturn($return);
            }     
        } 
        else//创建数据对象错误
        {
            $return['status']=0;
            $return['info']=$user->getError();
            $this->ajaxReturn($return);//返回错误信息
        }
    }

    public function deleteUser()//删除用户
    {
        if (session('status')==4)//只有管理员才能删除用户
        {
            if (!empty($_GET)) {
                $user = M('User');
                $where['id'] = I('get.id');//传回删除学生的id
                $date['status'] = 0;
                $result = $user->where($where)->save($date);//删除用户不删除用户在数据库中的数据 仅将其状态改为不可用
                if ($result)//删除成功
                {
                    $return['status']=1;
                    $this->ajaxReturn($return);
                } else//删除失败
                {
                    $return['status']=0;
                    $return['info']='删除失败';
                    $this->ajaxReturn($return);//返回错误信息
                }
            }
        } 
        else //权限不足
        {
            $return['status']=0;
            $return['info']='权限不足';
            $this->ajaxReturn($return);
        }
    }

    public function showAlterUser()//显示修改用户信息页面
    {
        if(session('status')==4)//管理员可修改
        {
            $user=M('User');
            $where['id']=I('get.id');
            $result=$user->where($where)->find();//渲染所修改用户的模板
            $this->assign('result',$result);
            $this->display('alterUser');//显示模板
        }
        else//用户自己可以修改
        {
            if(session('id')==I('get.id'))
            {
                $user=M('User');
                $where['id']=I('get.id');
                $result=$user->where($where)->find();//渲染所修改用户的模板
                $this->assign('result',$result);
                $this->display('alterUser');//显示模板
            }
            else//权限不足
            {
                $this->error('权限不足');
            }  
        }
    }

    public function getAlterUser()//获取修改用户信息
    {
        if(!empty($_GET))
        {
            $where['id']=I('get.id');
            $user=M('User');
            $result=$user->where($where)->find();//寻找要修改用户的信息
            $this->ajaxReturn($result);//返回信息
        }
    }

    public function alterUser()//修改用户信息
    { 
        if(!empty($_POST))//修改要修改的值
        {
            $user = D('User');
            $where['id'] = I('get.id');//传回修改用户的id
            $date['name'] = I('post.name');//更新的数据
            $date['sex'] = I('post.sex');//更新的数据
            $date['class'] = I('post.class');///更新的数据
            $date['school'] = I('post.school');//更新的数据
            $date['status'] = I('post.status');//更新的数据
            $date['group']=I('post.group');//更新的数据
            if (!$user->create($date))//创建user对象
            {
                $return['status']=0;
                $return['info']=$user->getError();
                $this->ajaxReturn($return);//返回错误信息
            }
            else
            {
                $result = $user->where($where)->save($date);//更新数据
                if ($result)//修改成功
                {
                    $return['status']=1;
                    $this->ajaxReturn($return);
                } 
                else//修改失败
                {
                    $return['status']=0;
                    $return['info']='修改失败';
                    $this->ajaxReturn($return);//返回错误信息
                }
            }      
        }
    }

    public function logout()//登出
    {
        session('status', null);//清空session
        session('id', null);//清空session
        $this->redirect('User/showLogin');//跳转到登陆界面
    }

    public function export()//导出用户Excel
    {
        if(session('status')>1)//权限验证
        {
            vendor('PHPExcel.Classes.PHPExcel');
            $Excel = new \PHPExcel();
            $user = M('User');
            $arr = $user->field('num,name,sex,class,school,group,status')->where('status>0')->select();//从User表中查询出要输出的用户的信息
             // 设置Excel的信息
            $Excel
                ->getProperties()
                ->setCreator("sz_manager")
                ->setLastModifiedBy("sz_manager")
                ->setTitle("User_EXCEL")
                ->setSubject("数据EXCEL导出")
                ->setDescription("数据EXCEL导出")
                ->setKeywords("excel")
                ->setCategory("result file");
            $Excel->setActiveSheetIndex(0)
                //第一行显示每一列的含义
                ->setCellValue('A' . 1, '学号')
                ->setCellValue('B' . 1, '姓名')
                ->setCellValue('C' . 1, '性别')
                ->setCellValue('D' . 1, '班级')
                ->setCellValue('E' . 1, '学院')
                ->setCellValue('F' . 1, '组别')
                ->setCellValue('G' . 1, '权限');
            foreach ($arr as $key => $val) { //从$arr的第0组开始
                $key = $key + 2;//从Excel的第2行开始赋值（Excel从第一行开始）
                $Excel->setActiveSheetIndex(0)
                 //对每一行的每一个字段赋值
                    ->setCellValueExplicit('A' . $key, $val['num'])
                    ->setCellValue('B' . $key, $val['name'])
                    ->setCellValue('C' . $key, $val['sex'])
                    ->setCellValue('D' . $key, $val['class'])
                    ->setCellValue('E' . $key, $val['school'])
                    ->setCellValue('F' . $key, $val['group'])
                    ->setCellValue('G' . $key, $val['status']);
            }
            $Excel->getActiveSheet()->setTitle('export');
            $Excel->setActiveSheetIndex(0);
            $name = 'User_Table.xlsx';//设置文件名
    
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment; filename=' . $name);
            header('Cache-Control: max-age=0');
    
            $ExcelWriter = \PHPExcel_IOFactory::createWriter($Excel, 'Excel2007');//文件输出
            $ExcelWriter->save('php://output');
            exit;
        }
    }

    public function import()//Excel导入用户
    {
        if(session('status')>1)//权限验证
        {
            vendor('PHPExcel.Classes.PHPExcel');//导入PHPExcel
            if (empty($_FILES)) {
                $this->display();//显示页面
            } else {
                $Upload = new \Think\Upload();//实例化上传类
                $Upload->exts = array('xlsx', 'xls');//设置限制文件上传类型
                $Upload->autoSub = false;//设置上传文件不创建子文件夹
                $Upload->rootPath = './Public/';//设置附件上传目录
                $Upload->savePath = '';//附件上传子目录
                $info = $Upload->upload();
                foreach ($info as $file) {
                    $savename = $file['savename'];
                    $startname = $file['name'];
                }
                $file_name = $Upload->rootPath . $savename;
                $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判断导入表格后缀格式
                if ($extension == 'xlsx') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                    $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                } else if ($extension == 'xls') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                    $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                }
                $sheet = $objPHPExcel->getSheet(0);
                $highestRow = $sheet->getHighestRow();//取得总行数
                $highestColumn = $sheet->getHighestColumn(); //取得总列数
                // D('sz_user')->execute('truncate table sz_user');
                for ($i = 2; $i <= $highestRow; $i++) {//从Excel中获取值 从第2行开始取值
                    $data['num'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue();
                    $data['name'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue();
                    $data['sex'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue();
                    $data['class'] = $objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue();
                    $data['school'] = $objPHPExcel->getActiveSheet()->getCell("E" . $i)->getValue();
                    $data['group'] = $objPHPExcel->getActiveSheet()->getCell("F" . $i)->getValue();
                    $data['status'] = $objPHPExcel->getActiveSheet()->getCell("G" . $i)->getValue();
                    D('user')->add($data);//将取得的数据插入数据库
                }
                $return['status']=1;
                $this->ajaxReturn($return);
            }
        }
    }

}